package com.ptswitch.material.pages.user;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;

import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.pages.base.MaterialBasePage;
import com.ptswitch.material.service.LoginInfoService;
import com.ptswitch.material.service.UserService;
import com.ptswitch.material.util.HlogConstants;

public class EditUser extends MaterialBasePage {
    @Inject
    private Logger logger;
    @Inject
    private UserService userSer;
    @Inject
    private LoginInfoService loginInfoSer;
    @InjectPage
    private ListUser listUser;
    @Property
    private Uzer user;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init(String id) {
        logger.trace("edit user ,now on activate");
        checkUserIsAdmin();
        //init for display or update
        user = userSer.findById(id);
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return user.getId();
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "update")
    Object update() {
        logger.trace("edit user,now update");
        checkUserIsAdmin();
        userSer.save(user);
        hlog(HlogConstants.updateUser, user);
        return listUser;
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "changePassword")
    Object changePassword() {
        checkUserIsAdmin();
        user.md5password();
        userSer.save(user);
        loginInfoSer.deleteByUsername(user.getUsername());
        hlog(HlogConstants.updateUserPassword, user);
        return listUser;
    }
}
